import React, { useState, useEffect } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Form, Input, Button, Modal, Select, Row, Col, InputNumber, Popconfirm, message } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import columnsData, { columnsDataType } from './data'
import { getPointRuleList, pointRuleListAdd, pointRuleDisable, checkCode } from './service'
import TableTitle from '../../components/TableTitle';
import { getCode } from '@/services/generateCode'

export default () => {
  const { Option } = Select;
  // 模态框控制
  const [isModalVisible, setIsModalVisible] = useState(false);
  // 添加用户数据表单验证 获取表单
  const [addFormRef] = Form.useForm();
  // 表头数据
  const columns: ProColumns<columnsDataType>[] = columnsData

  // 操作行数据 自定义操作行
  const actionRender: any = (text: any, record: any, index: number) => {
    return record.status === '0' ? [
      <Popconfirm
        title="是否失效该费率?"
        onConfirm={() => ruleDisable(record)}
        okText="是"
        cancelText="否"
      >
        <a key={record.status}>
          失效
        </a>
      </Popconfirm>
    ] : null
  }

  // point行数据 自定义靠右
  const pointRender: any = (text: any, record: any, index: number) =>
    [
      <p
        key='amount'
        style={{ textAlign: 'right', margin: 0 }}
      >
        {typeof text === 'number' ? text.toFixed(6) : null}
      </p>]

  // 自定义数据的表格头部数据
  columns.forEach((item: any) => {
    item.dataIndex === 'action' ? item.render = actionRender : undefined
    item.dataIndex === 'point' ? item.render = pointRender : undefined
  });

  // 新增按钮
  const addInfo = async () => {
    setIsModalVisible(true);
  }


  const actionCodeOnblur = async (e: any) => {
    e.persist()
    let pattern = /^[A-Za-z0-9].{19,19}$/
    console.log(e.target.value.match(pattern));

    if (e.target.value.match(pattern)) {
      let res = await checkCode({ actionCode: e.target.value })
      console.log(res);
      if (res.body.result === "行为编码已存在") {
        message.info('行为编码已存在,请重新输入行为编码')
      }
    } else {
      message.info('请输入由数字和字母组成的20位行为编码')
    }
  }


  // 新增确认
  const handleAddOk = () => {
    // 表单验证
    addFormRef.validateFields().then(async () => {
      // 获取表单信息
      var param = await addFormRef.getFieldsValue()
      pointRuleListAdd(param).then((res) => {
        // 刷新表格
        actionRef.current?.reload()
        // 重置表单
        addFormRef.resetFields();
        // 关闭模态框
        setIsModalVisible(false)
      })
    }).catch(() => { })
  }

  // 积分规则失效
  const ruleDisable = async (record: any) => {
    let { actionCode, actionName } = record
    let res = await pointRuleDisable({ actionCode, actionName })
    console.log(res);
    if (res) {
      actionRef.current?.reload()
      // 成功
      message.success('失效成功');
    }
  }

  // Table action 的引用，便于自定义触发
  const actionRef = React.useRef<ActionType>();

  return (
    <div>
      {/* Pro表格 */}
      <ProTable<columnsDataType>
        headerTitle={<TableTitle title='积分规则' />}
        scroll={{ x: 900 }}
        actionRef={actionRef}
        bordered
        // 表头
        columns={columns}
        // 请求获取的数据
        request={
          async (params = {}) => {
            console.log('!!!', params);
            return getPointRuleList({ ...params, pageNum: params.current }).then(res => {
              console.log(res);

              const result = {
                data: res.body.list,
                total: res.body.total,
                // success:res.success,
                // pageSize:res.pageSize,
                // current:res.current
              }
              return result
            })
          }
        }
        rowKey="actionCode"
        // 本地存储表格列的显示数据
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
        }}
        // 搜索框配置
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          pageSize: 10,
        }}
        dateFormatter="string"
        //设置工具栏按钮及事件
        toolBarRender={() => [
          <Button key="button" icon={<PlusOutlined />} type="primary" onClick={addInfo}>
            新增
          </Button>,
        ]}
      />
      {/* 新增模态框 */}
      <Modal
        title="积分发放规则配置"
        centered
        visible={isModalVisible}
        onOk={handleAddOk}
        onCancel={() => setIsModalVisible(false)}
        width={700}
      >
        <Form
          name="basic"
          form={addFormRef}
          labelCol={{ span: 24 }}
          wrapperCol={{ span: 24 }}
          autoComplete="off"
          initialValues={{
            state: 'effect'
          }}
        >
          <Row gutter={20}>
            <Col span={8}>
              <Form.Item
                label="行为编号"
                name="actionCode"
                extra={[<p key={'actionCodes'} style={{ fontSize: '12px' }}>请输入由字母和数字组成的20位编号</p>]}
                rules={[
                  {
                    // type: 'string',
                    required: true,
                    pattern: /^[A-Za-z0-9].{19,19}$/,
                    message: '请按要求输入行为编号'
                  }
                ]}
              >
                <Input
                  onBlur={actionCodeOnblur}
                  maxLength={20}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="行为名称"
                name="actionName"
                rules={[
                  {
                    required: true,
                    whitespace: true,
                    message: '请输入行为名称'
                  }
                ]}
              >
                <Input maxLength={20} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="有效天数"
                name="effectiveDay"
                rules={[
                  {
                    required: true,
                    message: '请输入生效天数',

                  }
                ]}
              >
                <InputNumber maxLength={4} style={{ width: '100%' }} precision={0} min={1} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={20}>
            <Col span={8}>
              <Form.Item
                label="激励分数"
                name="point"
                rules={[
                  {
                    required: true,
                    message: '请输入激励分数'
                  }
                ]}
              >
                <InputNumber maxLength={4} style={{ width: '100%' }} precision={0} min={1} />
              </Form.Item>
            </Col>
            <Col span={16}>
              <Form.Item
                label="规则描述"
                name="remark"
                rules={[
                  {
                    required: true,
                    whitespace: true,
                    message: '请输入规则描述'
                  }
                ]}
              >
                <Input maxLength={50} />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal >
    </div >
  );
};